pub mod db {
    use std::{env, sync::OnceLock, time::Duration};
    use sea_orm::{ConnectOptions, Database, DatabaseConnection, DbErr};

    #[derive(Debug, thiserror::Error)]
    pub enum DbLogicError {
        #[error(transparent)]
        DBError(#[from] DbErr),
        #[error(transparent)]
        Other(#[from] anyhow::Error),
        #[error("{0}")]
        Custom(String),
    }

    static DB_CLIENT: OnceLock<DatabaseConnection> = OnceLock::new();

    pub async fn establish_connection() -> DatabaseConnection {
        // 获取或初始化数据库连接
        if let Some(conn) = DB_CLIENT.get() {
            return conn.clone();
        }

        let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
        let mut opt = ConnectOptions::new(database_url);
        opt.max_connections(100)
            .min_connections(5)
            .connect_timeout(Duration::from_secs(8))
            .acquire_timeout(Duration::from_secs(8))
            .idle_timeout(Duration::from_secs(8))
            .max_lifetime(Duration::from_secs(8));
        
        let conn = Database::connect(opt).await.expect("Failed to connect to database");
        
        // 尝试设置全局连接，如果已经被设置则使用已有的
        let _ = DB_CLIENT.set(conn.clone());
        conn
    }
}